package com.computercourse.learning.service;

import com.computercourse.framework.domain.course.TeachplanMediaPub;
import com.computercourse.framework.domain.learning.CicLearningCourse;
import com.computercourse.framework.domain.learning.CicUserAnswer;
import com.computercourse.framework.domain.learning.CicUserComment;
import com.computercourse.framework.domain.learning.CicUserNote;
import com.computercourse.framework.domain.learning.respones.*;
import com.computercourse.framework.domain.task.CicTask;
import com.computercourse.framework.domain.task.CicTaskHis;
import com.computercourse.framework.exception.ExceptionCast;
import com.computercourse.framework.model.response.CommonCode;
import com.computercourse.framework.model.response.QueryResult;
import com.computercourse.framework.model.response.ResponseResult;
import com.computercourse.learning.client.CourseSearchClient;
import com.computercourse.learning.dao.*;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.jvm.hotspot.utilities.Assert;

import java.util.*;

/**
 * @author Feng.Yuan
 * @description
 * @date 2020/2/1 5:05 下午
 * @return
 */
@Service
public class LearningService {

    @Autowired
    private CourseSearchClient courseSearchClient;

    @Autowired
    private CicLearningCourseRepository cicLearningCourseRepository;

    @Autowired
    private CicTaskHisRepository cicTaskHisRepository;

    @Autowired
    private CicUserNoteRepository cicUserNoteRepository;

    @Autowired
    private CicUserAnswerRepository cicUserAnswerRepository;

    @Autowired
    private CicUserCommentRepository cicUserCommentRepository;

    //获取课程学习地址（视频播放地址）
    public GetMediaResult getMedia(String courseId, String teachplanId) {
        //校验学生的学生权限...

        //远程调用搜索服务查询课程计划所对应的课程媒资信息
        TeachplanMediaPub teachplanMediaPub = courseSearchClient.getMedia(teachplanId);
        if (teachplanMediaPub == null || StringUtils.isEmpty(teachplanMediaPub.getMediaUrl())) {
            //获取学习地址错误
            ExceptionCast.cast(LearningCode.LEARNING_GETMEDIA_ERROR);
        }
        return new GetMediaResult(CommonCode.SUCCESS, teachplanMediaPub.getMediaUrl());
    }


    //完成选课
    @Transactional
    public ResponseResult addCourse(String userId, String courseId, String valid, Date startTime, Date endTime, CicTask cicTask) {

        if (StringUtils.isEmpty(courseId)) {
            ExceptionCast.cast(LearningCode.LEARNING_GETMEDIA_ERROR);
        }

        if (StringUtils.isEmpty(userId)) {
            ExceptionCast.cast(LearningCode.CHOOSECOURSE_USERISNULL);
        }

        if (cicTask == null || StringUtils.isEmpty(cicTask.getId())) {
            ExceptionCast.cast(LearningCode.CHOOSECOURSE_TASKISNULL);
        }
        //查询历史任务
        Optional<CicTaskHis> optional = cicTaskHisRepository.findById(cicTask.getId());
        if (optional.isPresent()) {
            return new ResponseResult(CommonCode.SUCCESS);
        }
        CicLearningCourse cicLearningCourse = cicLearningCourseRepository.findByUserIdAndCourseId(userId, courseId);

        if (cicLearningCourse == null) {
            //没有选课记录则添加
            cicLearningCourse = new CicLearningCourse();
            cicLearningCourse.setUserId(userId);
            cicLearningCourse.setCourseId(courseId);
            cicLearningCourse.setValid(valid);
            cicLearningCourse.setStartTime(startTime);
            cicLearningCourse.setEndTime(endTime);
            cicLearningCourse.setStatus("501001");
            cicLearningCourseRepository.save(cicLearningCourse);
        } else {
            //有选课记录则更新日期
            cicLearningCourse.setValid(valid);
            cicLearningCourse.setStartTime(startTime);
            cicLearningCourse.setEndTime(endTime);
            cicLearningCourse.setStatus("501001");
            cicLearningCourseRepository.save(cicLearningCourse);
        }

        //向历史任务表插入记录
        Optional<CicTaskHis> optionalCicTaskHis = cicTaskHisRepository.findById(cicTask.getId());

        if (!optionalCicTaskHis.isPresent()) {
            //添加历史任务
            CicTaskHis cicTaskHis = new CicTaskHis();
            BeanUtils.copyProperties(cicTask, cicTaskHis);
            cicTaskHisRepository.save(cicTaskHis);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }


    public GetLearningNoteResult getAllNotesList(String courseId) {

        List<CicUserNote> cicUserNotes = cicUserNoteRepository.findAllByCourseIdOrderByNoteTimeDesc(courseId);
        return new GetLearningNoteResult(CommonCode.SUCCESS, cicUserNotes);

    }

    public GetLearningNoteResult getAllPerfectNotes(String courseId) {

        List<CicUserNote> cicUserNotes = cicUserNoteRepository.findAllByCourseIdAndPerfectNoteEqualsOrderByModifyTimeDesc(courseId, 1);
        return new GetLearningNoteResult(CommonCode.SUCCESS, cicUserNotes);

    }

    @Transactional
    public ResponseResult deleteNoteByCourseIdAndNoteId(String courseId, String noteId) {

        CicUserNote cicUserNote = new CicUserNote();
        cicUserNote.setNoteId(noteId);
        cicUserNote.setCourseId(courseId);
        try {
            cicUserNoteRepository.delete(cicUserNote);
        } catch (Exception e) {
            return new DeleteResponseResult(CommonCode.FAIL, "删除失败");
        }
        return new ResponseResult(CommonCode.SUCCESS);

    }

    @Transactional
    public ResponseResult saveNote(String courseId, String noteContent) {

        CicUserNote cicUserNote = new CicUserNote();
        cicUserNote.setCourseId(courseId);
        cicUserNote.setNoteContent(noteContent);
        cicUserNote.setNoteTime(Calendar.getInstance().getTime());
        CicUserNote save = cicUserNoteRepository.save(cicUserNote);
        if (Objects.nonNull(save)) {
            return new ResponseResult(CommonCode.SUCCESS);
        } else {
            return new DeleteResponseResult(CommonCode.FAIL, "保存失败");
        }
    }

    @Transactional
    public ResponseResult saveAsPerfectNoteByCourseId(String courseId, String noteId) {

        CicUserNote courseIdAndNoteId = cicUserNoteRepository.findByCourseIdAndNoteId(courseId, noteId);
        if (Objects.nonNull(courseIdAndNoteId)) {
            courseIdAndNoteId.setPerfectNote(1);
            courseIdAndNoteId.setModifyTime(Calendar.getInstance().getTime());
            cicUserNoteRepository.save(courseIdAndNoteId);
            return new ResponseResult(CommonCode.SUCCESS);

        } else {
            return new DeleteResponseResult(CommonCode.FAIL, "保存失败");
        }
    }

    @Transactional
    public ResponseResult saveAnswer(String courseId, String answerTitle, String answerContent) {

        CicUserAnswer cicUserAnswer = new CicUserAnswer();
        cicUserAnswer.setCourseId(courseId);
        cicUserAnswer.setAnswerTitle(answerTitle);
        cicUserAnswer.setAnswerContent(answerContent);
        cicUserAnswer.setAnswerTime(Calendar.getInstance().getTime());
        CicUserAnswer save = cicUserAnswerRepository.save(cicUserAnswer);
        if (Objects.nonNull(save)) {
            return new ResponseResult(CommonCode.SUCCESS);
        } else {
            return new DeleteResponseResult(CommonCode.FAIL, "保存失败");
        }
    }

    @Transactional
    public ResponseResult saveAsPerfectAnswerByCourseId(String courseId, String answerId) {

        CicUserAnswer andAnswerId = cicUserAnswerRepository.findCicUserAnswerByCourseIdAndAndAnswerId(courseId, answerId);
        if (Objects.nonNull(andAnswerId)) {
            andAnswerId.setPerfectAnswer(1);
            cicUserAnswerRepository.save(andAnswerId);
            return new ResponseResult(CommonCode.SUCCESS);

        } else {
            return new DeleteResponseResult(CommonCode.FAIL, "保存失败");
        }
    }

    @Transactional
    public ResponseResult deleteNoteByCourseIdAndAnswerId(String courseId, String answerId) {

        CicUserAnswer cicUserAnswer = new CicUserAnswer();
        cicUserAnswer.setAnswerId(answerId);
        cicUserAnswer.setCourseId(courseId);
        try {
            cicUserAnswerRepository.delete(cicUserAnswer);
        } catch (Exception e) {
            return new DeleteResponseResult(CommonCode.FAIL, "删除失败");
        }
        return new ResponseResult(CommonCode.SUCCESS);

    }


    public GetLearningAnswerResult getAllAnswersList(String courseId) {

        List<CicUserAnswer> allByCourseId = cicUserAnswerRepository.findAllByCourseIdOrderByAnswerTimeDesc(courseId);
        return new GetLearningAnswerResult(CommonCode.SUCCESS, allByCourseId);

    }


    public GetLearningAnswerResult getAllPerfectAnswers(String courseId) {

        List<CicUserAnswer> perfectAnswers = cicUserAnswerRepository.findAllByCourseIdAndPerfectAnswerEqualsOrderByModifyTimeDesc(courseId, 1);
        return new GetLearningAnswerResult(CommonCode.SUCCESS, perfectAnswers);

    }


    public GetLearningCommentResult getAllCommentList(String courseId) {

        List<CicUserComment> allByCourseId = cicUserCommentRepository.findAllByCourseIdOrderByCommentTimeDesc(courseId);
        return new GetLearningCommentResult(CommonCode.SUCCESS, allByCourseId);

    }

    @Transactional
    public ResponseResult saveComment(String courseId, String commentContent, Integer commentCourseGrade) {

        CicUserComment cicUserComment = new CicUserComment();
        cicUserComment.setCourseId(courseId);
        cicUserComment.setCommentContent(commentContent);
        cicUserComment.setCommentCourseGrade(commentCourseGrade);
        cicUserComment.setCommentTime(Calendar.getInstance().getTime());
        CicUserComment save = cicUserCommentRepository.save(cicUserComment);
        if (Objects.nonNull(save)) {
            return new ResponseResult(CommonCode.SUCCESS);
        } else {
            return new DeleteResponseResult(CommonCode.FAIL, "保存失败");
        }
    }

    @Transactional
    public ResponseResult cancelNote(String courseId, String noteId) {

        int i = cicUserNoteRepository.cancelPerfectNote(courseId, noteId);
        if (i > 0) {
            return new ResponseResult(CommonCode.SUCCESS);
        } else {
            return new DeleteResponseResult(CommonCode.FAIL, "取消失败");
        }
    }

    @Transactional
    public ResponseResult cancelAnswer(String courseId, String answerId) {

        int i = cicUserAnswerRepository.cancelPerfectNote(courseId, answerId);
        if (i > 0) {
            return new ResponseResult(CommonCode.SUCCESS);
        } else {
            return new DeleteResponseResult(CommonCode.FAIL, "取消失败");
        }
    }

    public GetChooseCourseResult getChooseCourseList(Integer page, Integer size,String userId) {

        Pageable pageRequest = PageRequest.of(page, size);
        Page<CicLearningCourse> pageList = cicLearningCourseRepository.queryAllByUserId(userId,pageRequest);

        QueryResult<CicLearningCourse> queryResult = new QueryResult<>();
        List<CicLearningCourse> learningCourses = pageList.getContent();
        queryResult.setList(learningCourses);
        queryResult.setTotal(pageList.getTotalElements());
        return new GetChooseCourseResult(CommonCode.SUCCESS, queryResult);
    }


}

